package com.heima.service.impl;

import com.heima.mapper.HomePageMapper;
import com.heima.service.HomePageService;
import com.heima.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class HomePageServiceImpl implements HomePageService {
    @Autowired
    private HomePageMapper homePageMapper;
    @Override
    public BaseInfoVo getBaseInfo(LocalDate beginCreateTime, LocalDate endCreateTime) {
        log.info("基础数据，查询时间：{} - {}",beginCreateTime,endCreateTime);
        endCreateTime=endCreateTime.plusDays(1);
        //获取线索数量
        Integer cluesNum=homePageMapper.getCluesNum(beginCreateTime,endCreateTime);
        //获取商机数量
        Integer businessNum=homePageMapper.getBusinessNum(beginCreateTime,endCreateTime);
        //获取客户数量
        Integer contractNum=homePageMapper.getContractNum(beginCreateTime,endCreateTime);
        //获取销售额
        List<BigDecimal> salesAmountList=homePageMapper.getSalesAmount(beginCreateTime,endCreateTime);
        //获取今日新增线索
        LocalDate now = LocalDate.now();
        Integer todayCluesNum=homePageMapper.getTodayCluesNum(now);
        //获取今日新增商机
        Integer todayBusinessNum=homePageMapper.getTodayBusinessNum(now);
        //获取今日新增合同/客户数量
        Integer todayContractNum=homePageMapper.getTodayContractNum(now);
        //获取今日销售额
        BigDecimal todaySalesAmount=homePageMapper.getTodaySalesAmount(now,now.plusDays(1));
        //待跟进线索
        Integer tofollowCluesNum=homePageMapper.getTofollowedCluesNum(beginCreateTime,endCreateTime.plusDays(1));
        //待跟进商机
        Integer tofollowedBusinessNum=homePageMapper.getTofollowedBusinessNum(beginCreateTime,endCreateTime);
        //待分配线索
        Integer toallocatedCluesNum=0;
        Integer toallocatedBusinessNum=0;
        if (CollectionUtils.isEmpty(salesAmountList)){
            BigDecimal salesAmount= BigDecimal.valueOf(0);
             BigDecimal totalSalesAmount = BigDecimal.valueOf(0);
            return new BaseInfoVo(cluesNum,businessNum,
                    0,salesAmount,
                    todayCluesNum,todayBusinessNum,
                    0,totalSalesAmount,
                    0, 0,
                    0,0);
        }
        BigDecimal amountSum=BigDecimal.ZERO;
            for (BigDecimal salesAmount : salesAmountList) {
                amountSum=amountSum.add(salesAmount);
            }
        //封装数据
        return new BaseInfoVo(cluesNum,businessNum,contractNum,amountSum,
                todayCluesNum,todayBusinessNum,todayContractNum,todaySalesAmount,
                tofollowCluesNum,tofollowedBusinessNum,toallocatedCluesNum,toallocatedBusinessNum);
    }

    @Override
    public TodayInfo getTodayInfo(LocalDate now) {
        now=LocalDate.now();
        Integer todayCluesNum=homePageMapper.getTodayCluesNum(now);
        Integer todayBusinessNum = homePageMapper.getTodayBusinessNum(now);
        Integer todayContractNum = homePageMapper.getTodayContractNum(now);
        BigDecimal todaySalesAmount = homePageMapper.getTodaySalesAmount(now, now.plusDays(1));
        return new TodayInfo(todayCluesNum,todayBusinessNum,todayContractNum,todaySalesAmount);
    }

    @Override
    public TodoInfo getTodoInfo(LocalDate beginCreateTime, LocalDate endCreateTime) {
        log.info("待办事项，查询时间：{} - {}",beginCreateTime,endCreateTime);
        //待跟进线索
        Integer tofollowCluesNum=0;
        Integer tofollowedBusinessNum=0;
        //待分配线索
        Integer toallocatedCluesNum=0;
        Integer toallocatedBusinessNum=0;
        return new TodoInfo(tofollowCluesNum,tofollowedBusinessNum,toallocatedCluesNum,toallocatedBusinessNum);
    }

    /**
     * 商机变化统计榜
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<BusinessChangeVo> businessChangeStatistics(LocalDate beginCreateTime, LocalDate endCreateTime) {
        log.info("商机变化统计，查询时间：{} - {}",beginCreateTime,endCreateTime);
        //获取部门员工数据
        List<UserListVo> userListVoList =homePageMapper.getEmp(beginCreateTime,endCreateTime);
        List<BusinessChangeVo> businessChangeVos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userListVoList)){
            for (UserListVo user : userListVoList) {
                BusinessChangeVo businessChangeVo = new BusinessChangeVo();
                String createBy = user.getCreateBy();
                Integer deptId = user.getDeptId();
                log.info("查询部门：{}",deptId);
                DeptVo deptVo =homePageMapper.getByDeptId(deptId);
                if (deptVo == null){
                    continue;
                }
                String deptName = deptVo.getDeptName();
                //获取对应员工的商机数量
                Integer userId = user.getUserId();
                Integer byBusinessNum=homePageMapper.getByBusinessNum(userId,beginCreateTime,endCreateTime);
                //获取对应员工的商机转化数/合同数
                Integer num = homePageMapper.getByCotractNum(userId,beginCreateTime, endCreateTime);
                businessChangeVo.setCreate_by(createBy);
                businessChangeVo.setDeptName(deptName);
                businessChangeVo.setNum(num);
                Double doubleNum = num*1.0 / byBusinessNum;
                if (doubleNum < 0) {
                    throw new RuntimeException("百分比计算有误");
                } else if (doubleNum >= 1) {
                    businessChangeVo.setRadio(100);
                    businessChangeVos.add(businessChangeVo);
                    continue;
                }
                int percentage = (int) Math.round(doubleNum * 100);
                businessChangeVo.setRadio(percentage);
                businessChangeVos.add(businessChangeVo);
            }
        }
        return businessChangeVos;
    }

    /**
     * 首页获取线索转化榜
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<SalesStatisticVo> salesStatistic(LocalDate beginCreateTime, LocalDate endCreateTime) {
        log.info("线索转化榜，查询时间：{} - {}",beginCreateTime,endCreateTime);

        List<UserListVo> userListVoList = homePageMapper.getEmp(beginCreateTime, endCreateTime);
        ArrayList<SalesStatisticVo> salesStatisticVos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userListVoList)){
            for (UserListVo userListVo : userListVoList) {
                SalesStatisticVo salesStatisticVo = new SalesStatisticVo();
                salesStatisticVo.setCreate_by(userListVo.getCreateBy());
                Integer deptId = userListVo.getDeptId();
                DeptVo deptVo = homePageMapper.getByDeptId(deptId);
                if (deptVo == null){
                    continue;
                }
                salesStatisticVo.setDeptName(deptVo.getDeptName());
                //获取对应员工的线索转化数
                Integer userId = userListVo.getUserId();
                Integer businessNum=homePageMapper.getByBusinessNum(userId,beginCreateTime,endCreateTime);
                salesStatisticVo.setNum(businessNum);
                //获取对应员工的线索总数量
                Integer cluesNum = homePageMapper.getTotalCluesNum(userId,beginCreateTime, endCreateTime);
                Double doubleNum = businessNum*1.0 / cluesNum;
                if (doubleNum < 0) {
                    throw new RuntimeException("百分比计算有误");
                } else if (doubleNum >= 1) {
                    salesStatisticVo.setRadio(100);
                    salesStatisticVos.add(salesStatisticVo);
                    continue;
                }
                int percentage = (int) Math.round(doubleNum * 100);
                salesStatisticVo.setRadio(percentage);
                salesStatisticVos.add(salesStatisticVo);
            }
        }
        return salesStatisticVos;
    }

    /**
     * 获取漏斗图数据
     * @param
     * @param
     * @return
     */
    @Override
    public ReportVo getVuInerabilityMap(String begin, String end) {

        log.info("漏斗图数据，查询时间：{} - {}",begin,end);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate beginDate = LocalDate.parse(begin, formatter);
        LocalDate endDate = LocalDate.parse(end, formatter);
        Integer cluesNum = homePageMapper.getCluesNum(beginDate, endDate);
        //获取有效线索数
        Integer effectiveCluesNum=homePageMapper.getEffectiveCluesNum(beginDate, endDate);
        //获取有效商机数
        Integer businessNum = homePageMapper.getBusinessNum(beginDate, endDate);
        //获取客户数/合同数
        Integer contractNum = homePageMapper.getContractNum(beginDate, endDate);
        return new ReportVo(cluesNum,effectiveCluesNum,businessNum,contractNum);
    }
}
